package csm.batteryinfo;

import java.text.DecimalFormat;

import com.mopub.mobileads.MoPubView;

import csm.batteryinfo.R;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.BatteryManager;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;

public class InfoDisplayActivity extends Activity implements OnClickListener {
	private TextView batteryLevelTextView;
	private TextView technologyTextView;
	private TextView temperatureTextView;
	private TextView healthTextView;
	private TextView statusTextView;
	private RelativeLayout background;
	private LinearLayout linearLayout;

	private MoPubView mAdView;

	private Typeface font;

	private SharedPreferences settings;

	private boolean isCelsiusScaleUsed;

	private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context arg0, Intent intent) {
			int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);

			batteryLevelTextView.setText(String.valueOf(level) + "%");
			if (level > 75) {
				batteryLevelTextView.setTextColor(Color.GREEN);
			} else if (level > 25) {
				batteryLevelTextView.setTextColor(Color.YELLOW);
			} else if (level > 15) {
				batteryLevelTextView.setTextColor(Color.rgb(255, 80, 40));// orange
			} else {
				batteryLevelTextView.setTextColor(Color.RED);
			}

			String tech = intent
					.getStringExtra(BatteryManager.EXTRA_TECHNOLOGY);
			technologyTextView.setText(getText(R.string.technology) + ": "
					+ tech);

			double temperature = intent.getIntExtra(
					BatteryManager.EXTRA_TEMPERATURE, 37);
			if (isCelsiusScaleUsed)
				temperature /= 10;
			else
				temperature = ((temperature / 10) * 1.8) + 32;

			DecimalFormat df = new DecimalFormat();
			df.applyLocalizedPattern("@@##");

			temperatureTextView.setText(getText(R.string.temperature)
					+ ": "
					+ df.format(temperature)
					+ " "
					+ (isCelsiusScaleUsed ? getText(R.string.degrees_celsius)
							: getText(R.string.degrees_fahrenheit)));

			int health = intent.getIntExtra(BatteryManager.EXTRA_HEALTH,
					BatteryManager.BATTERY_HEALTH_UNKNOWN);
			String healthStr = (String) getText(R.string.unknown);
			switch (health) {
			case BatteryManager.BATTERY_HEALTH_DEAD:
				healthStr = (String) getText(R.string.dead);
				break;
			case BatteryManager.BATTERY_HEALTH_GOOD:
				healthStr = (String) getText(R.string.good);
				break;
			case BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE:
				healthStr = (String) getText(R.string.over_voltage);
				break;
			case BatteryManager.BATTERY_HEALTH_OVERHEAT:
				healthStr = (String) getText(R.string.over_heat);
				break;
			case BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE:
				healthStr = (String) getText(R.string.unspecified_failure);
				break;
			}
			healthTextView.setText(getText(R.string.health) + ": " + healthStr);

			int pluggedIdx = intent
					.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
			String pluggedInto = "";
			switch (pluggedIdx) {
			case BatteryManager.BATTERY_PLUGGED_AC:
				pluggedInto = (String) getText(R.string.plugged_into_ac);
				break;
			case BatteryManager.BATTERY_PLUGGED_USB:
				pluggedInto = (String) getText(R.string.plugged_into_usb);
				break;
			}

			int statusIdx = intent.getIntExtra(BatteryManager.EXTRA_STATUS,
					BatteryManager.BATTERY_STATUS_UNKNOWN);
			String statusStr = (String) getText(R.string.unknown);
			switch (statusIdx) {
			case BatteryManager.BATTERY_STATUS_CHARGING:
				statusStr = (String) getText(R.string.charging);
				break;
			case BatteryManager.BATTERY_STATUS_DISCHARGING:
				statusStr = (String) getText(R.string.discharging);
				break;
			case BatteryManager.BATTERY_STATUS_FULL:
				statusStr = (String) getText(R.string.full);
				break;
			case BatteryManager.BATTERY_STATUS_NOT_CHARGING:
				statusStr = (String) getText(R.string.not_charging);
				break;
			}
			statusTextView.setText(getText(R.string.status) + ": " + statusStr
					+ pluggedInto);
		}
	};

	/** Called when the activity is first created. */
	@SuppressWarnings("deprecation")
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		batteryLevelTextView = (TextView) findViewById(R.id.batteryLevelTextView);

		// Create the labels
		technologyTextView = new TextView(this);
		temperatureTextView = new TextView(this);
		healthTextView = new TextView(this);
		statusTextView = new TextView(this);

		linearLayout = (LinearLayout) findViewById(R.id.infoLinearLayout);
		linearLayout.setOrientation(LinearLayout.VERTICAL);

		background = (RelativeLayout) findViewById(R.id.BackgroundRelativeLayout);

		font = Typeface.createFromAsset(getAssets(), "digital-7.ttf");
		batteryLevelTextView.setTypeface(font);

		Display display = getWindowManager().getDefaultDisplay();

		int height = display.getHeight();
		int width = display.getWidth();
		float currentTVWidth = height / 5;

		batteryLevelTextView.setPadding(0, height / 6, 0, 0);
		batteryLevelTextView.setTextSize(currentTVWidth);

		while (batteryLevelTextView.getPaint().measureText("100%") > width) {
			currentTVWidth -= 2.0f;
			batteryLevelTextView.setTextSize(currentTVWidth);
		}

		batteryLevelTextView.setOnClickListener(this);

		settings = Prefs.get(this);
		// AdMob side
		// try {
		// // Ads section
		// AdView adView = (AdView) findViewById(R.id.adView1);
		// AdRequest ar = new AdRequest();
		// ar.setGender(AdRequest.Gender.MALE);
		// adView.loadAd(ar);
		// } catch (Exception e) {
		// Log.e("BatteryInfo",
		// "There was an excepion when trying to load the Ads", e);
		// e.printStackTrace();
		// }

		try {
			mAdView = (MoPubView) findViewById(R.id.adview);
			// Enter your Ad Unit ID from www.mopub.com
			mAdView.setAdUnitId("agltb3B1Yi1pbmNyDQsSBFNpdGUYwc7TEAw");
			mAdView.loadAd();
		} catch (Throwable t) {
		}
	}

	@Override
	public void onResume() {
		super.onResume();

		background.setOnClickListener(this);

		linearLayout.removeAllViews();

		if (settings.getBoolean(SettingsDisplayActivity.TECHNOLOGY_KEY, true)) {
			linearLayout.addView(technologyTextView);
		}
		if (settings.getBoolean(SettingsDisplayActivity.TEMPERATURE_KEY, true)) {
			linearLayout.addView(temperatureTextView);
		}
		if (settings.getBoolean(SettingsDisplayActivity.HEALTH_KEY, true)) {
			linearLayout.addView(healthTextView);
		}
		if (settings.getBoolean(SettingsDisplayActivity.STATUS_KEY, true)) {
			linearLayout.addView(statusTextView);
		}

		isCelsiusScaleUsed = (SettingsDisplayActivity.CELSIUS_SCALE == settings
				.getInt(SettingsDisplayActivity.TEMP_SCALE,
						SettingsDisplayActivity.CELSIUS_SCALE) ? true : false);

		this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(
				Intent.ACTION_BATTERY_CHANGED));
	}

	@Override
	public void onPause() {
		super.onPause();
		try {
			this.unregisterReceiver(mBatInfoReceiver);
		} catch (Exception e) {
		}
		;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		try {
			mAdView.destroy();
		} catch (Throwable t) {
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.settingsMenuItem:
			openSettingsActivity();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	protected void openBatteryConsumptionActivity() {
		try {
			Intent intent = new Intent();
			intent.setAction(Intent.ACTION_VIEW);
			intent.setComponent(new ComponentName("com.android.settings",
					"com.android.settings.fuelgauge.PowerUsageSummary"));
			this.startActivity(intent);
		} catch (Throwable e) {
			// do nothing
		}
	}

	protected void openSettingsActivity() {
		Intent intent = new Intent(this, SettingsDisplayActivity.class);
		this.startActivity(intent);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.batteryLevelTextView:
			openBatteryConsumptionActivity();
			break;

		case R.id.BackgroundRelativeLayout:
			this.finish();
			break;
		}
	}
}